package com.example.dingtalklogin.service.executor;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.dingtalklogin.common.exception.CheckException;
import com.example.dingtalklogin.dao.User;
import com.example.dingtalklogin.dao.UserRepository;
import com.example.dingtalklogin.service.dto.UserLoginCmd;
import com.example.dingtalklogin.service.dto.data.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserLoginCmdExe {

    private UserRepository userRepository;

    @Autowired
    public UserLoginCmdExe(UserRepository userRepository){
        this.userRepository = userRepository;
    }

    public UserDto execute(UserLoginCmd cmd){
        cmd.validate();

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, cmd.getUsername());

        User user = userRepository.getOne(queryWrapper);

        if(user == null){
            throw new CheckException("用户不存在!");
        }

        if(!BCrypt.checkpw(cmd.getPassword(), user.getPassword())){
            throw new CheckException("密码错误！");
        }

        UserDto userDto = new UserDto();
        userDto.setUsername(user.getUsername());
        userDto.setId(user.getId());
        if(StringUtils.hasLength(user.getDingtalkUnionId())){
            userDto.setBindingDingtalk(true);
        }
        return userDto;
    }
}
